package net.sf.cldsql.sql2json.main;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.cldsql.dj.container.DiServletUtl;
import net.sf.cldsql.dj.mvc.DiRoute;
import net.sf.cldsql.dj.mvc.DiService;
import net.sf.cldsql.dj.mvc.DiServlet;
import net.sf.cldsql.dj.utl.DiException;
import net.sf.cldsql.sql2json.utl.SjContext;
import net.sf.cldsql.sql2json.utl.SjServiceUtl;


/**
 * DataServlet
 */
public class SjServlet extends DiServlet {
    
    final Logger log = LoggerFactory.getLogger(SjServlet.class);
    
    /** serial */
    private static final long serialVersionUID = -4091354248462399878L;
    
    /** constructor */
    public SjServlet() {
    }
    
    /** init */
    public void init () {
        log.info("Servlet init begin.");
        DiServletUtl.init(getServletContext());
        container = DiServletUtl.get(getServletContext());
        log.info("Servlet init end.");
    }
    
    protected void service(final HttpServletRequest req, final HttpServletResponse res) {
        try {
            long beginTs = System.currentTimeMillis();
            log.info("Servlet request begin.");
            SjController controller = container.get(SjController.class);
            DiRoute route = controller.find(new SjContext(req));
            if(req.getProtocol().equals("HTTP/1.0")) {
                res.setHeader("Pragma","no-cache");
            } else if(req.getProtocol().equals("HTTP/1.1")) {
                res.setHeader("Cache-Control","no-cache");
            }
            res.setDateHeader("Expires",0);
            res.setHeader("Content-Type", "application/json; charset=UTF-8");
            res.setCharacterEncoding("UTF-8");
            res.setHeader("Content-Type", "text/javascript");
            
            log.debug("Call service route {}.", route);
            res.getWriter().println(SjServiceUtl.invoke(container, route));
            
            long endTs = System.currentTimeMillis();
            log.info("Servlet request finished in {} ms.", endTs - beginTs);
        } catch (Exception e) {
            throw new DiException(e);
        }
    }

}
